#!/usr/bin/env python
# encoding: utf-8
# Date: 2017-06-19 09:07:37
# file:views.py
# Email: wang521kang@outlook.com
# Author: 王康
from commodity.models import Commodity, CommodityImg
from shopping_cart.models import ShoppingCart
from utils.views import request_parms_check, get_json


@request_parms_check(commodity_id=('商品id', 'r,int'), com_num=('商品数量', 'r,int'))
def add_shopping_cart(request, commodity_id, com_num):
    user_id = request.user.id
    query = ShoppingCart.objects.filter(user_id=user_id, commodity_id=commodity_id).count()
    if query == 0:
        shoppingcart = ShoppingCart()
        shoppingcart.user_id = user_id
        shoppingcart.commodity_id = commodity_id
        shoppingcart.num = com_num
        shoppingcart.save()
    else:
        q = ShoppingCart.objects.filter(user_id=user_id, commodity_id=commodity_id).all()
        if q[0].is_active:
            for item in q[1:]:
                item.delete()
            obj = q[0]
            obj.num += com_num
            obj.save()
        else:
            for item in q[1:]:
                item.delete()
            obj = q[0]
            obj.is_active = True
            obj.num = com_num
            obj.save()
    return get_json(True, '添加成功')


@request_parms_check()
def query_shopping_cart(request):
    user_id = request.user.id
    query = ShoppingCart.objects.filter(user_id=user_id, is_active=True).all()
    l = []
    for obj in query:
        res = {}
        com = Commodity.objects.get(id=obj.commodity_id)
        img_num = CommodityImg.objects.filter(id=obj.commodity_id).count()
        img = CommodityImg.objects.filter(id=obj.commodity_id)
        res['id'] = com.id
        res['name'] = com.name
        res['price'] = com.price
        res['preferential'] = com.preferential
        if img_num > 0:
            res['img_url'] = img[0].img_url
        res['classification'] = com.commodity_classification.classification
        res['num'] = obj.num
        l.append(res)
    return get_json(True, '添加成功', l)
